package com.hua.yuan.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hua.yuan.base.Constents;
import com.hua.yuan.common.BaseActivity;
import com.hua.yuan.R;
import com.hua.yuan.manager.user.UserManagerModule;
import com.hua.yuan.manager.user.business.callback.IUserCallback;
import com.hua.yuan.provider.user.IUserProvider;
import com.hua.yuan.provider.user.User;
import com.hua.yuan.ui.data.LoginDataRequest;
import com.hua.yuan.userlogin.UserLoginModule;
import com.hua.yuan.userlogin.business.callback.IUserLoginCallback;
import com.hua.yuan.userlogin.business.result.UserSigBean;
import com.hua.yuan.util.SystemUtils;
import com.hua.yuan.util.ToastUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cm.hua.yuan.common.utils.PreferenceUtils;
import okhttp3.Call;

/**
 * Created by huangyang on 2018/5/9.
 * 注册界面
 */

public class RegisterActivity extends BaseActivity implements
        View.OnClickListener,IUserCallback<IUserProvider>
{

    private ImageView backImage;
    private TextView titleView;

    private EditText registerPhone;
    private TextView registerGetCode;
    private EditText registerInputCode;
    private EditText registerPwd;
    private TextView registerLogin;

    private RelativeLayout loginLoadView;


    public static int CODE_TIME = 60;//测试是3秒

    private int codeNum = 0;


    private final String TAG=RegisterActivity.class.getName();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();
        initData();
    }

    private void initView() {

        backImage = findViewById(R.id.backImage);
        titleView = findViewById(R.id.titleView);

        registerPhone = findViewById(R.id.registerPhone);
        registerGetCode = findViewById(R.id.registerGetCode);
        registerInputCode = findViewById(R.id.registerInputCode);
        registerPwd = findViewById(R.id.registerPwd);
        registerLogin = findViewById(R.id.registerLogin);

        loginLoadView = findViewById(R.id.loginLoadView);

    }

    private void initData() {


        backImage.setOnClickListener(this);
        registerGetCode.setOnClickListener(this);
        registerLogin.setOnClickListener(this);

        titleView.setText("快速注册");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backImage:
                finish();
                break;
            case R.id.registerGetCode:
                //获取验证码

                String msg = registerGetCode.getText().toString().trim();
                if ("发送验证码".equals(msg)) {
                    getCodeFun();
                }


                break;
            case R.id.registerLogin:
                //登录
                registerFun();
                break;
        }
    }


    /**
     * 注册功能
     */
    private void registerFun() {

        final String phone = registerPhone.getText().toString().trim();
        String code = registerInputCode.getText().toString().trim();
        final String pwd = registerPwd.getText().toString().trim();

        if (phone.length() == 0) {
            ToastUtil.showShortToast("手机号不能为空");
            return;
        }
        if (phone.length() != 11) {
            ToastUtil.showShortToast("请输入正确的手机号");
            return;
        }

        if (code.length() == 0) {
            ToastUtil.showShortToast("请先获取验证码");
            return;
        }

        if (pwd.length() == 0) {
            ToastUtil.showShortToast("请设置密码");
            return;
        }

        if (pwd.length() < 6) {
            ToastUtil.showShortToast("密码不能少于6位");
            return;
        }

        loginLoadView.setVisibility(View.VISIBLE);

//        LoginDataRequest.register(phone, pwd, code, new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//
//
//                if (isFinishing()) {
//                    return;
//                }
//
//                if (loginLoadView != null) {
//                    loginLoadView.setVisibility(View.GONE);
//                }
//
//                ToastUtil.showShortToast("注册失败");
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
//
//                if (isFinishing()) {
//                    return;
//                }
//
//
//                if (loginLoadView != null) {
//                    loginLoadView.setVisibility(View.GONE);
//                }
//
//                try {
//                    JSONObject jsonObject = new JSONObject(response);
//
//                    if (!jsonObject.isNull("errno")) {
//
//                        String code = jsonObject.getString("errno");
//                        if ("0".equals(code)) {
//
//                            PreferenceUtils.setString(Constents.USER_NAME, phone);
//
//                            PreferenceUtils.setBoolean(Constents.IS_LOGIN, true);
//
//                            //登录一下
//
//                            loginFun(phone, pwd);
//
//                        } else if ("102".equals(code)) {
//
//                            ToastUtil.showShortToast("验证码错误");
//
//                        } else {
//
//                            ToastUtil.showShortToast("注册失败");
//
//                        }
//
//
//                    }
//
//
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//
//            }
//        });


        Map userMap=new HashMap<>();
        userMap.put(UserManagerModule.MOBILE,phone);
        userMap.put(UserManagerModule.PASSWORD,pwd);
        userMap.put(UserManagerModule.SMS_CODE,code);
        IUserProvider userProvider=UserLoginModule.getInstance().getProvider();
        UserManagerModule.getInstance().getUserManager().registerUser(userMap,userProvider,this);
    }

    @SuppressLint("SetTextI18n")
    private void getCodeFun() {

        String phone = registerPhone.getText().toString().trim();

        if (phone.length() == 0) {
            ToastUtil.showShortToast("手机号不能为空");
            return;
        }
        if (phone.length() != 11) {
            ToastUtil.showShortToast("请输入正确的手机号");
            return;
        }

        codeNum = CODE_TIME;

        registerGetCode.setText("还剩" + codeNum + "秒");
        registerGetCode.setBackgroundResource(R.drawable.log_get_code_1_shape);

        handler.sendEmptyMessageDelayed(1, 1000);

        LoginDataRequest.getMsgCode(phone, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {


            }

            @Override
            public void onResponse(String response, int id) {


            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:

                    if (codeNum == 0) {


                        if (registerGetCode != null) {
                            registerGetCode.setBackgroundResource(R.drawable.log_bg_get_code);
                            registerGetCode.setText("发送验证码");
                        }

                    } else {
                        codeNum = codeNum - 1;
                        if (registerGetCode != null) {
                            registerGetCode.setBackgroundResource(R.drawable.log_get_code_1_shape);
                            registerGetCode.setText("还剩" + codeNum + "秒");
                        }
                        sendEmptyMessageDelayed(1, 1000);
                    }
                    break;
            }

        }
    };

    @Override
    public void onResult(@NonNull final IUserProvider pUserInfo) {
        SystemUtils.isMainThread(TAG);
        if(pUserInfo==null){
            ToastUtil.showShortToast("注册失败");
            return;
        }
        ToastUtil.showShortToast("注册成功");
        startActivity(new Intent(this,LoginActivity.class));
        if(!isFinishing()){
            finish();
        }

    }

    @Override
    public void onError(final Throwable e) {
        SystemUtils.isMainThread(TAG);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showShortToast("注册失败");
            }
        });
    }
}
